package com.itheima.web;

import com.itheima.pojo.*;
import com.itheima.service.BrowseGoodsRecordService;
import com.itheima.service.ItemService;
import com.itheima.service.PurchaseHistoryService;
import com.itheima.service.ShoppingCartService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@WebServlet("/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
    private BrowseGoodsRecordService browseGoodsRecordService = new BrowseGoodsRecordService();
    private PurchaseHistoryService purchaseHistoryService = new PurchaseHistoryService();
    private ShoppingCartService shoppingCartService = new ShoppingCartService();
    private ItemService itemService = new ItemService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 调用ItemService完成查询
        List<Item> items = itemService.selectAll();

        //1. 判断session中是否有user
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        //2. 判断user是否为null
        if (user != null) {
            // 登录过了，展示推荐商品

            /*
            算法思路：
            1. 对每个用户分别查询BrowseGoodsRecord、PurchaseHistory和ShoppingCart表,获得其itemName
            2. 对于每个商品,如果这个商品的itemName在BrowseGoodsRecord、PurchaseHistory和ShoppingCart中,它的推荐度就+1
            */

            Integer userId = user.getId();

            List<BrowseGoodsRecord> browseGoodsRecords = browseGoodsRecordService.selectByUserId(userId);
            List<PurchaseHistory> purchaseHistories = purchaseHistoryService.selectByBuyerId(userId);
            List<ShoppingCart> shoppingCartGoods = shoppingCartService.selectByBuyerId(userId);

            // 用于记录每个itemId的推荐度
            HashMap<Integer, Integer> recommendationDict = new HashMap<>();
            // 初始化recommendationDict,设置推荐度为0
            for (Item item : items) {
                recommendationDict.put(item.getId(), 0);
            }

            for (Item item : items) {
                for (BrowseGoodsRecord browseGoodsRecord : browseGoodsRecords) {
                    if (browseGoodsRecord.getItemName().equals(item.getItemName())) {
                        Integer value = recommendationDict.get(item.getId()) + 1;
                        recommendationDict.put(item.getId(), value);
                    }
                }

                for (PurchaseHistory purchaseHistory : purchaseHistories) {
                    if (purchaseHistory.getItemId().equals(item.getId())) {
                        Integer value = recommendationDict.get(item.getId()) + 1;
                        recommendationDict.put(item.getId(), value);
                    }
                }

                for (ShoppingCart shoppingCartGood : shoppingCartGoods) {
                    if (shoppingCartGood.getItemId().equals(item.getId())) {
                        Integer value = recommendationDict.get(item.getId()) + 1;
                        recommendationDict.put(item.getId(), value);
                    }
                }
            }

            // 创建一个List对象，用于存储HashMap中的所有键值对
            List<Map.Entry<Integer, Integer>> list = new ArrayList<>(recommendationDict.entrySet());

            // 使用Collections.sort()方法对List对象进行排序，排序的依据是HashMap的value值，从大到小排序
            Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
                public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                    return o2.getValue().compareTo(o1.getValue());
                }
            });

            // 创建一个新的List对象，用于存储value最大的三个键
            List<Integer> maxKeys = new ArrayList<>();

            // 遍历排序后的List对象，并将前三个键存储到新的List对象中
            int count = 0;
            for (Map.Entry<Integer, Integer> entry : list) {
                if (count < 3) {
                    maxKeys.add(entry.getKey());
                    count++;
                } else {
                    break;
                }
            }

//            // 输出结果
//            System.out.println("HashMap: " + recommendationDict);
//            System.out.println("Value最大的三个键: " + maxKeys);

            List<Item> recommendedItems = new ArrayList<>();
            for (Integer itemId : maxKeys) {
                recommendedItems.add(itemService.selectById(itemId));
            }

//            System.out.println(recommendedItems);

            request.setAttribute("recommendedItems", recommendedItems);

            // 用于前端判断用户是否登录
            request.setAttribute("loggedIn", true);
        }

        // --------------------分割线--------------------

        //2. 存入request域中
        request.setAttribute("items", items);

        //3. 转发到home-page.jsp
        request.getRequestDispatcher("/home-page.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
